package com.haotunet.app.goldtreasure.activity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.eventbus.WechatBackMessageEvent;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.UserInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Config;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.TitleView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.umeng.message.UmengRegistrar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.tongdun.android.shell.FMAgent;

public class LoginActivity extends BaseActivity {
    @InjectView(R.id.title_view)
    TitleView titleView;
    @InjectView(R.id.et_phone)
    EditText etPhone;
    @InjectView(R.id.iv_delete_phone)
    ImageView ivDeletePhone;
    @InjectView(R.id.et_pwd)
    EditText etPwd;
    @InjectView(R.id.iv_pwd_status)
    ImageView ivPwdStatus;
    @InjectView(R.id.text)
    TextView text;
    private boolean pwdStatus = false;
    private ShareStore mStore;
    private final int FORGET_PASSWORD = 1;
    private final int WECHAT_CHECK_PHONE = 2;
    private String wechatCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);
        mStore = new ShareStore(this);
        initView();
    }

    private void initView() {
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText(getString(R.string.login));
        titleView.getRightText().setVisibility(View.VISIBLE);
        titleView.getRightText().setText(getString(R.string.register));
        titleView.getBackView().setVisibility(View.VISIBLE);
        initEditext();
    }

    private void initEditext() {
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    ivDeletePhone.setVisibility(View.VISIBLE);
                } else {
                    ivDeletePhone.setVisibility(View.GONE);
                }
            }
        });
    }

    private void login() {

        String username = etPhone.getText().toString().trim();
        String password = etPwd.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            return;
        }
        if (TextUtils.isEmpty(password)) {
            return;
        }
        Land(username, password);
    }

    private void Land(String username, String password) {
        String device_token = UmengRegistrar.getRegistrationId(LoginActivity.this);
        String blackBox = FMAgent.onEvent(this);
        ActionUtil actionUtil = new ActionUtil(LoginActivity.this);
        actionUtil.CheckLoginInfo(blackBox, username, password, device_token, Config.getImei(LoginActivity.this));
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                UserInfo info = (UserInfo) model;
                if (info == null) {
                    UIHelper.showToast(LoginActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (info.getErrorMsg() != null) {
                    UIHelper.showToast(LoginActivity.this, info.getErrorMsg());
                } else {
                    UIHelper.showToast(LoginActivity.this, getString(R.string.login_success));
                    storeUserInfo(info);
                    LoginActivity.this.finish();
                }
            }


        });
    }

    private void storeUserInfo(UserInfo info) {
        LoginActivity.this.setResult(RESULT_OK);
        mStore.putBoolean(Strs.IS_LOGIN, true);
        mStore.putInt(Strs.IS_HAD_TRADING_PWD, info.getIsHadTradingPassword());
        mStore.putInt(Strs.IS_HAD_BANK_CARD, info.getIsHadBankCard());
        mStore.commit();
        DBOpenHelper helper = new DBOpenHelper(LoginActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        String mobile = info.getUserName();
        String sql = "select * from HJB_USER where mobile = " + "'" + mobile + "'";
        Cursor rawQuery = db.rawQuery(sql, null);
        if (rawQuery.getCount() != 0) {
            helper.updateUser(mobile, "0", info);
        } else {
            helper.insertUser("0", info);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatBackEvent(WechatBackMessageEvent event) {
        wechatCode = event.getCode();
        wechatAuth(event.getCode());
    }

    private void wechatAuth(String code) {
        String device_token = UmengRegistrar.getRegistrationId(LoginActivity.this);
        String blackBox = FMAgent.onEvent(this);
        ActionUtil actionUtil = new ActionUtil(LoginActivity.this);
        actionUtil.wechatAuth(code, device_token, Config.getImei(LoginActivity.this), blackBox, Config.getStringMetaData(LoginActivity.this, "UMENG_CHANNEL"));
        actionUtil.setOnPassBackListener(new OnPassBackListener() {
            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()){
                    return;
                }
                UserInfo info = (UserInfo) model;
                if (info == null) {
                    UIHelper.showToast(LoginActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (info.getErrorMsg() != null) {
                    UIHelper.showToast(LoginActivity.this, info.getErrorMsg());
                } else {
                    if ("true".equals(info.getStatus())) {
                        storeUserInfo(info);
                        LoginActivity.this.finish();
                    } else {
                        ActivityUtils.gotoFindPwd(LoginActivity.this, "绑定手机号，便于下次快捷登录", "确认", WECHAT_CHECK_PHONE, wechatCode);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.iv_back, R.id.txt_right, R.id.iv_delete_phone, R.id.iv_pwd_status, R.id.btn_login, R.id.btn_forget_pwd, R.id.wechat_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.txt_right:
                ActivityUtils.gotoRegister(LoginActivity.this);
                break;
            case R.id.iv_delete_phone:
                etPhone.setText("");
                break;
            case R.id.iv_pwd_status:
                if (pwdStatus) {
                    pwdStatus = false;
                    etPwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivPwdStatus.setSelected(false);
                } else {
                    pwdStatus = true;
                    etPwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivPwdStatus.setSelected(true);
                }
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_forget_pwd:
                ActivityUtils.gotoFindPwd(LoginActivity.this, "请使用您注册的手机号码找回登录密码", "下一步", FORGET_PASSWORD, "");
                break;
            case R.id.wechat_login:
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "goldplusgold";
                MyApplication.wxapi.sendReq(req);
                break;
        }
    }
}
